package com.qijian.flowable.common.listener;

import com.google.common.collect.Maps;
import lombok.RequiredArgsConstructor;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.flowable.spring.boot.EngineConfigurationConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * flowable 全局监听器配置类
 *
 * @author qijian
 */
@Configuration
@RequiredArgsConstructor
public class FlowableListenerConfig {

    // flowable监听级别参照 {@link FlowableEngineEventType} org.flowable.common.engine.api.delegate.event
    /**
     * 任务节点前置监听
     */
    private static final String FLOWABLE_TASK_NODE_COMPLETED_LISTENER = "TASK_COMPLETED";
    private static final String FLOWABLE_TASK_NODE_CREATE_LISTENER = "TASK_CREATED";

    // 自己建立监听类实现FlowableEventListener接口
    /**
     * 任务节点前置监听
     */
    private final TaskEndListener taskEndListener;
    private final TaskBeforeListener taskBeforeListener;
    private final ProcessEndListener processEndListener;

    /**
     * 将自定义监听器纳入flowable监听
     *
     * @return org.flowable.spring.boot.EngineConfigurationConfigurer<org.flowable.spring.SpringProcessEngineConfiguration>
     * @author: Lu Yang
     * @date: 2019/5/4 21:05
     */
    @Bean
    public EngineConfigurationConfigurer<SpringProcessEngineConfiguration> globalListenerConfigurer() {
        return engineConfiguration -> engineConfiguration.setTypedEventListeners(this.customFlowableListeners());
    }

    /**
     * 监听类配置 {@link } flowable监听器级别
     *
     * @return java.util.Map<java.lang.String, java.util.List < org.flowable.common.engine.api.delegate.event.FlowableEventListener>>
     * @author: Lu Yang
     * @date: 2019/5/4 20:58
     */
    private Map<String, List<FlowableEventListener>> customFlowableListeners() {
        Map<String, List<FlowableEventListener>> listenerMap = Maps.newHashMap();
        // 任务完成
        listenerMap.put(FlowableEngineEventType.TASK_COMPLETED.name(), new ArrayList<>(Collections.singletonList(getTaskEndListener())));
        // 任务开始
        listenerMap.put(FlowableEngineEventType.TASK_CREATED.name(), new ArrayList<>(Collections.singletonList(getTaskBeforeListener())));
        // 流程完成结束节点
        listenerMap.put(FlowableEngineEventType.PROCESS_COMPLETED.name(), Collections.singletonList(getProcessEndListener()));
        return listenerMap;
    }

    public ProcessEndListener getProcessEndListener() {
        return processEndListener;
    }

    public TaskEndListener getTaskEndListener() {
        return taskEndListener;
    }

    public TaskBeforeListener getTaskBeforeListener() {
        return taskBeforeListener;
    }
}
